package com.zr.d_c.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zr.d_c.model.Role;
import com.zr.d_c.model.User;
import com.zr.d_c.service.RoleService;
import com.zr.d_c.service.UserInfoService;
import com.zr.d_c.service.UserService;
import com.zr.d_c.serviceimpl.RoleServiceImpl;
import com.zr.d_c.serviceimpl.UserInfoServiceImpl;
import com.zr.d_c.serviceimpl.UserServiceImpl;

import net.sf.json.JSONObject;

public class LoginController extends HttpServlet {

	UserInfoService loginserivce = new UserInfoServiceImpl();
	UserService userservice = new UserServiceImpl();
	RoleService roleservice = new RoleServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = req.getSession();
		String uname = req.getParameter("uname");
		String upsw = req.getParameter("upsw");
		User u = userservice.getUserByUnameAndUpsw(uname, upsw);
		if(u != null){
			session.setAttribute("currentUser", u);
			session.setAttribute("errorMsg", "");
			int rid = u.getRid();
			Role r = roleservice.getRoleByRid(rid);
			String currentUserName = loginserivce.getCurrentUserNameByUnameAndUpsw(u);
			session.setAttribute("currentUserName", currentUserName);
			session.setAttribute("currentRole", r.getRname());
			req.getRequestDispatcher("main.jsp").forward(req, resp);
		}else{
			session.setAttribute("errorMsg", "用户名或密码错误");
			resp.sendRedirect("login.jsp");
		}
		
	}
}
